* August 21, 2015
* This code prepares the single-product firm data for the production-function estimation

use ${rootfile}/rootfile,clear
	* construct higher order terms on inputs
	local M=3
	local N=3
	forval i=1/`M' {
		gen l_s`i'=l^(`i')
		gen m`i'=m^(`i')
		gen k_s`i'=k^(`i')
		*interaction terms
		forval j=1/`N' {
			gen l_s`i'm`j'=l^(`i')*m^(`j')
			gen l_s`i'k_s`j'=l^(`i')*k^(`j')
			gen k_s`i'm_s`j'=k^(`i')*m^(`j')
			gen m`i'k_s`j'=m^(`i')*k^(`j')
			}
		}
		gen lmk_s=l*m*k

*creating interaction terms between \phi(x,z):
*** MTB: CHANGE IN ORIGINAL CODE: USE FIRM-YEAR AND FIRM-PRODUCT-YEAR SUPPORT INDICATOR IN PLACE OF TARIFFS
*	cap drop p_qt_* p_tf_*
*	forval i=1/3 {
*		gen tau_in`i'=p_qt^`i'
*		gen tau_ou`i'=p_tf^`i'
*		}
gen tau_in1=treated_p
gen tau_ou1=treated
		gen l_s_tau_i=l*tau_in1
		gen m_tau_i=m*tau_in1
		gen k_s_tau_i=k*tau_in1
		gen l_s_tau_o=l*tau_ou1
		gen m_tau_o=m*tau_ou1
		gen k_s_tau_o=k*tau_ou1


* compute market share for each product before selecting single product firms:
	gen Q_j=exp(q_j)
	bysort pcode12 unit year: egen TOTQ=sum(Q_j)
	gen msq=Q_j/TOTQ
	drop TOTQ Q_j
	gen R_j=exp(r_j)
	bysort pcode12 unit year: egen TOTR=sum(R_j)
	gen msr=R_j/TOTR
	bysort pnic4 year: egen TOTR4d=sum(R_j)
	gen msr4d=R_j/TOTR4d


* compute dummy for probability of remaining single-product
	preserve
		keep fid year n
		duplicates drop
		sort fid year
		tsset fid year
		g single_next = f.n==n & n==1
		bys fid: egen maxyr = max(year)
		replace single_next = . if year==maxyr
			drop maxyr n
		save tmp_fidn,replace
	restore
merge m:1 fid year using tmp_fidn, assert(3) nogenerate
	erase tmp_fidn.dta
	tsset fup12 year
save rootfile_temp, replace

*use rootfile_temp,clear
*	keep fup12 locationcode
*	duplicates drop
*	sort fup12 
*save locationdata, replace


use rootfile_temp,clear
	gsort fid year -sv
	by fid year: g rank = _n
	keep if rank==1 & n==1
	drop rank
save singleproduct_data,replace




